<template>
  <div class="login-container">
    <div class="login-box">
      <h2>用户登录</h2>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="0"
        size="large"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="email">
          <el-input
            v-model="loginForm.email"
            placeholder="请输入邮箱"
            prefix-icon="Message"
          >
          </el-input>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          >
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            class="login-button"
            :loading="loading"
            native-type="submit"
          >
            登录
          </el-button>
        </el-form-item>

        <div class="form-footer">
          <router-link to="/auth/register" class="register-link">
            还没有账号？立即注册
          </router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Message, Lock } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user.js'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref(null)
const loginForm = reactive({
  email: '',
  password: ''
})

const loginRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
    { min: 5, max: 50, message: '邮箱长度应在5到50个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
    { max: 72, message: '密码长度不能超过72个字符', trigger: 'blur' }
  ]
}

const loading = ref(false)

const handleLogin = async (e) => {
  if (e) e.preventDefault()
  if (!loginFormRef.value) return

  try {
    // 表单验证
    const valid = await loginFormRef.value.validate().catch(() => false)
    if (!valid) {
      return false
    }

    // 设置加载状态
    loading.value = true
    
    // 发送登录请求
    const { email, password } = loginForm
    await userStore.login({ email, password })
    
    // 初始化用户状态
    await userStore.init()
    
    // 登录成功提示
    ElMessage.success('登录成功')
    
    // 处理重定向
    const redirect = router.currentRoute.value.query.redirect
    if (redirect && typeof redirect === 'string' && !redirect.includes('/login')) {
      // 确保重定向地址不包含登录页，防止循环重定向
      await router.push(redirect)
    } else {
      // 如果没有重定向地址或重定向地址无效，则跳转到首页
      await router.push('/')
    }
  } catch (error) {
    // 错误处理
    console.error('登录失败:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status
    })

    // 根据错误类型显示不同的错误消息
    if (error.response?.status === 401) {
      ElMessage.error('邮箱或密码错误')
    } else if (error.response?.status === 429) {
      ElMessage.error('登录尝试次数过多，请稍后再试')
    } else if (error.response?.status === 422) {
      ElMessage.error('请输入正确的邮箱和密码格式')
    } else {
      ElMessage.error(error.response?.data?.message || '登录失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: calc(100vh - 64px);
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}

.login-box {
  width: 100%;
  max-width: 400px;
  padding: 2rem;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-box h2 {
  text-align: center;
  margin-bottom: 2rem;
  color: #303133;
}

.login-button {
  width: 100%;
}

.form-footer {
  margin-top: 1rem;
  text-align: center;
}

.register-link {
  color: #409EFF;
  text-decoration: none;
  font-size: 0.9rem;
}

.register-link:hover {
  color: #66b1ff;
}
</style>